package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor =Exception.class )
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //参数合法性检查
        if(dto==null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //通过id查询当前用户是否在App端有用户 ap_user_realname+ap_user表
        Integer userRealNameId = dto.getId();
        ApUserRealname apUserRealname = getOne(
                Wrappers.<ApUserRealname>lambdaQuery()
                        .eq(ApUserRealname::getId, userRealNameId)
                        .eq(ApUserRealname::getStatus, 1)
        );
        if (apUserRealname==null){
            log.error("apUserRealname is Null userRealnameId:"+userRealNameId);
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApUser apUser = apUserMapper.selectOne(
                Wrappers.<ApUser>lambdaQuery()
                        .eq(ApUser::getId, apUserRealname.getUserId())
                        .eq(ApUser::getStatus, 0)
        );
        if (apUser==null){
            log.error("apUserRealname apUser is Null userRealnameId:{}, userId:{} ", dto.getId(), apUserRealname.getUserId());
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //保存用户信息
        apUserRealname.setId(userRealNameId);
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotEmpty(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //认证状态
        if (AdminConstants.PASS_AUTH.equals(status)){
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser==null){
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }
//            int i=1/0;
            boolean flag = createApAuthor(wmUser);
            if (!flag){
                CustException.cust(AppHttpCodeEnum.APAUTHOR_ADD_ERROR);
            }
            //更新App用户状态
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }

        // TODO 发送邮件通知
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据用户的审核状态查询用户信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult loadListByStatus(AuthDto dto) {
        //参数合法性检查
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //条件查询 0创建中  1待审核  2审核不通过    9审核通过
        IPage<ApUserRealname> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper=new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageResult=page(page,wrapper);
        PageResponseResult result=new PageResponseResult();
        result.setCurrentPage(dto.getPage());
        result.setSize(dto.getSize());
        result.setTotal((int) pageResult.getTotal());
        result.setData(pageResult.getRecords());

        return result;
    }

    /**
     *  创建作者信息
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        //1 查询当前作者是否存在，不存在则新增
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2); // 自媒体人类型
            apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
            apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
            ResponseResult result = articleFeign.save(apAuthor);
            if (result.getCode()==0){
                return true;
            }
        }
        return false;
    }

    /**
     * 创建自媒体
     * @param authDto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(AuthDto authDto,ApUser apUser){
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser==null){
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setSalt(apUser.getSalt());  // 盐
            wmUser.setPassword(apUser.getPassword()); // 密码
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setApUserId(apUser.getId());  // app端用户id
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
            wmUser =  wemediaFeign.save(wmUser); // 主要的目的是返回新增后的主键
            if (wmUser!=null){
                return wmUser;
            }
        }
        return null;
    }
}
